/*
 *  ook_ship.mm
 *  template
 *
 *  Created by Ryan Layne on 11/1/09.
 *  Copyright 2009 Spiral Nebula Development. All rights reserved.
 *
 */

#include "../src/sio2/sio2.h"

#include "ook_ship.h"

void Ship::Setup()
{
	SIO2object *_SIO2object = ( SIO2object * )sio2ResourceGetObject( sio2->_SIO2resource, "object/Cube" );
	_SIO2object->_SIO2objectphysic->_btRigidBody->setCollisionFlags( _SIO2object->_SIO2objectphysic->_btRigidBody->getCollisionFlags() | _SIO2object::CF_KINEMATIC_OBJECT);
	_SIO2object->_SIO2objectphysic->_btRigidBody->setActivationState(DISABLE_DEACTIVATION);
	curspeed = 0.0f;
	speed = 500.0f;
	accel = 1.0f;
	turnspeed = 3.0f;
	spin = false;
}

void Ship::Accel()
{
	curspeed += accel;
	if (curspeed > speed) curspeed = speed;
	SIO2object *_SIO2object = ( SIO2object * )sio2ResourceGetObject( sio2->_SIO2resource, "object/Cube" );
	_SIO2object->_SIO2objectphysic->_btRigidBody->setLinearVelocity( btVector3(_SIO2object->_SIO2objectphysic->_btRigidBody->getLinearVelocity().x() * accel,
																			   _SIO2object->_SIO2objectphysic->_btRigidBody->getLinearVelocity().y() * accel,
																			   _SIO2object->_SIO2objectphysic->_btRigidBody->getLinearVelocity().z() ) );
	// printf("\n%f\n", curspeed);
}

void Ship::Decel()
{
	
}

void Ship::Left()
{
	curd += turnspeed;
	// printf("Left");
}

void Ship::Right()
{
	curd -= turnspeed;
	// printf("Right");
}

void Ship::Rotate()
{
	if (spin == true) {
		SIO2object *_SIO2object = ( SIO2object * )sio2ResourceGetObject( sio2->_SIO2resource, "object/Cube" );
		curd = sio2RoundAngle(_SIO2object->_SIO2transform->rot->z);
		d.x = sio2->_SIO2window->touch[ 0 ]->x - 240.0f;
		d.y = sio2->_SIO2window->touch[ 0 ]->y - 160.0f;
		d.z = 0.0f;
		tard = sio2RoundAngle(sio2GetAngleZ(&d));
		if (fabsf(curd - tard) >= turnspeed) {
			calc = curd;
			if (fabsf(curd - tard) > 180.0f) {
				if (curd < tard) {
					calc += 360.0f;
				} else {
					tard += 360.0f;
				}
			}
			if (tard - calc >= 0.0f) {
				Left();
				if (curd < 0.0f) curd += 360.0f;
			} else {
				Right();
				if (curd > 359.0f) curd -= 360.0f;
			}
		} else {
			curd = tard;
		}
		_SIO2object->_SIO2transform->rot->z = curd;
		sio2TransformBindMatrix(_SIO2object->_SIO2transform);
		// printf("\n%f\n", curd);
	}
}

void Ship::Update()
{
	Rotate();
	if (spin == true) {
		pyth = sqrt(powf(fabsf(sio2->_SIO2window->touch[ 0 ]->x - 240.0f), 2.0f) + powf(fabsf(sio2->_SIO2window->touch[ 0 ]->y - 160.0f), 2.0f));
		// printf("\n%f\n", pyth);
		if(pyth > 80.0f) {
			Accel();
		}
	}
}